/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.manager;

import br.com.foxline.enums.PartQuality;
import br.com.foxline.enums.TypeDocument;
import br.com.foxline.model.*;
import br.com.foxline.service.*;
import br.com.foxline.util.ConverterImg;
import br.com.foxline.util.Msg;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.SelectEvent;

/**
 *
 * @author roniere
 */
@ManagedBean
@SessionScoped
public class ManagerCep implements Serializable {

    @EJB
    StampService stampService;
    @EJB
    TypeStampService typeStampService;
    @EJB
    CharterService charterService;
    @EJB
    PeopleService peopleService;
    @EJB
    QualityService qualityService;
    @EJB
    NatureWritingService  natureWritingService;
    @EJB
    CityService cityService;
    @EJB
    ActCepService actCepService;
    
    private Charter charter;
    private ActCep actCep;
    private People people;
    private Part part;
    private List<Part> parts;
    private Stamp stamp;
    private List<Stamp> stamps;
    private TypeStamp typeStampObj;
    private Annex annex;
    private List<Annex> annexs;
    private NatureWriting natureWriting;
    private City city;
    private List<ActCep> actCeps;
    private List<NatureWriting> natureWritings;

    @PostConstruct
    public void init() {
        
        charter = new Charter();
        people = new People();
        people.setTipoDocumento(TypeDocument.CPF);
        part = new Part();
        parts = new ArrayList<Part>();
        stamp = new Stamp();
        stamps = new ArrayList<Stamp>();
        typeStampObj = new TypeStamp();
        annexs = new ArrayList<Annex>();
        city = new City();
        
        actCep = new ActCep();
        natureWriting = new NatureWriting();
        
        try{
            city = cityService.autocomplete("Parnaíba").get(0);
        }catch(Exception e){
            System.err.println("BANCO NÃO POSSUI PARNAÍBA");
            e.printStackTrace();
        }
            
        actCeps = new ArrayList<ActCep>();
        natureWritings = new ArrayList<NatureWriting>();
        
    }
    
    public ActCep getActCep() {
        return actCep;
    }

    public void setActCep(ActCep actCep) {
        this.actCep = actCep;
    }

    public List<ActCep> getActCeps() {
        return actCeps;
    }

    public void setActCeps(List<ActCep> actCeps) {
        this.actCeps = actCeps;
    }

    public List<NatureWriting> getNatureWritings() {
        return natureWritings;
    }

    public void setNatureWritings(List<NatureWriting> natureWritings) {
        this.natureWritings = natureWritings;
    }

    
    
    
    public City getCity() {
        return city;
    }

    public void setCity(City city) {
        this.city = city;
    }

    
    public NatureWriting getNatureWriting() {
        return natureWriting;
    }

    public void setNatureWriting(NatureWriting natureWriting) {
        this.natureWriting = natureWriting;
    }
    

    public Annex getAnnex() {
        return annex;
    }

    public void setAnnex(Annex annex) {
        this.annex = annex;
    }

    public List<Annex> getAnnexs() {
        return annexs;
    }

    public void setAnnexs(List<Annex> annexs) {
        this.annexs = annexs;
    }

    public TypeStamp getTypeStampObj() {
        return typeStampObj;
    }

    public void setTypeStampObj(TypeStamp typeStampObj) {
        this.typeStampObj = typeStampObj;
    }

    public Part getPart() {
        return part;
    }

    public void setPart(Part part) {
        this.part = part;
    }

    public Stamp getStamp() {
        return stamp;
    }

    public void setStamp(Stamp stamp) {
        this.stamp = stamp;
    }

    public List<Part> getParts() {
        return parts;
    }

    public void setParts(List<Part> parts) {
        this.parts = parts;
    }

    public Charter getCharter() {
        return charter;
    }

    public void setCharter(Charter charter) {
        this.charter = charter;
    }

    public People getPeople() {
        return people;
    }

    public List<Stamp> getStamps() {
        return stamps;
    }

    public void setStamps(List<Stamp> stamps) {
        this.stamps = stamps;
    }

    public void setPeople(People people) {
        this.people = people;
    }

    public void typeDocumentPeople() {
        System.err.println(people.getTipoDocumento());
    }

    public List<SelectItem> typeDocumentList() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (TypeDocument tipo : TypeDocument.values()) {
            if (tipo != TypeDocument.OAB) {
                items.add(new SelectItem(tipo.getType(), tipo.getName()));
            }
        }
        return items;
    }

    public List<SelectItem> partQualitytList() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (PartQuality tipo : PartQuality.values()) {
            items.add(new SelectItem(tipo));
        }
        return items;
    }

    public void addParts() {

        if (people.getName().isEmpty() || people.getName() == null) {
            Msg.messagemError("O nome da parte é obrigatório");
            return;
        }

        if (part.getPartQuality() != null) {
            part.setPartQuality(qualityService.find(part.getPartQuality().getId()));
        }

        part.setPeople(people);
        parts.add(part);
        people = new People();
        people.setTipoDocumento(TypeDocument.CPF);
        part = new Part();

    }

    public void remove(int p) {
        parts.remove(p);
    }

    public void addStamps() {
        stamp.setTypeStamp(typeStampService.find(typeStampObj.getId()));
        stamps.add(stamp);
        stamp = new Stamp();
    }

    public void handle(FileUploadEvent event) throws IOException {
        handleAux(event.getFile().getContents(), event.getFile().getFileName(),
                event.getFile().getContentType(), event.getFile().getInputstream());
    }

    private void handleAux(byte[] imageBytes, String nome, String tipo, InputStream is) throws IOException {

        byte[] bytes = null;

        annex = new Annex();
        if (tipo.equalsIgnoreCase("image/tiff")) {
            bytes = ConverterImg.convertTiffToJpg(is);
            annex.setType("jpeg");
            annex.setDescription(nome.replaceAll("tif|tiff", "jpeg"));
        } else {
            bytes = imageBytes;
            annex.setType(tipo);
            annex.setDescription(nome);
        }
        if (bytes != null) {
            annex.setFileByte(bytes);
            annexs.add(annex);
            System.err.println("Annexoo..." + annexs.size());
            annex = new Annex();
            Msg.messagemWarn("Anexado");
        }

    }
    
    public void findNatureWriting(SelectEvent event){
        try{
            charter.setNatureWriting(natureWritingService.find( ((NatureWriting) event.getObject()).getId() ));
        }catch(Exception e){
            System.err.println(e);
        }
    }

    public void create() {
        System.err.println("CRIANDO ESCRITURA");
        
        if(actCep != null && actCep.getId() != null){
            charter.setActCep(actCep);
        }
        if(natureWriting != null && natureWriting.getId() != null)
            charter.setNatureWriting(natureWritingService.find(natureWriting.getId()));
        if(city != null && city.getId() != null)
            charter.setCity(cityService.find(city.getId()));
        charter.setAnnex(annexs);
        charter.setStamp(stamps);
        People person = null;
        for (Part p : parts) {
            System.err.println(p.getPeople());
            if (p.getPeople().getId() == null) {
                peopleService.save(p.getPeople());
            } else {
                peopleService.update(p.getPeople());
            }

        }

        charter.setParts(parts);
        System.err.println(charter);
        charterService.save(charter);
        init();

    }

    public void ajaxVerifyPeopleExist() {
        String doc = "";
        if (people.getTipoDocumento() == TypeDocument.CNPJ) {
            doc = people.getCnpj();
        } else if (people.getTipoDocumento() == TypeDocument.CPF) {
            doc = people.getCpf();
        } else if (people.getTipoDocumento() == TypeDocument.OAB) {
            doc = people.getOAB();
        }
        if (doc == null || doc.isEmpty()) {
            return;
        }
        People pe = peopleService.existPeople(people.getTipoDocumento(), doc);
        if (pe != null) {
            people = pe;

            if (people.getCnpj() != null) {
                people.setTipoDocumento(TypeDocument.CNPJ);
            } else if (people.getCpf() != null) {
                people.setTipoDocumento(TypeDocument.CPF);
            } else if (people.getOAB() != null) {
                people.setTipoDocumento(TypeDocument.OAB);
            }
        }
    }
    
    public void loadActCep(){
        actCeps = actCepService.findAll();
    }
    public void loadNature(){
        natureWritings = natureWritingService.findAll();
    }
    public void initActCep(){
        actCep = new ActCep();
    }
    public void initNature(){
        natureWriting = new NatureWriting();
    }
}
